package com.csdj.web;

import com.alibaba.fastjson.JSON;
import com.csdj.entity.Employee;
import com.csdj.service.EmployeeService;
import com.csdj.service.impl.EmployeeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * packageName com.csdj.web
 *
 * @author winver
 * @version 1.0
 * @className LoginServlet
 * @date 2024/11/27
 * @description TODO
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //编码设置
        resp.setContentType("text/html;charset=utf-8");


        //获取请求参数  根据情况判断参数的合理性
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        //调用业务层
        EmployeeService employeeService = new EmployeeServiceImpl();

        Map<String, Object> resultMap = employeeService.login(name, password);
        System.out.println(resultMap.get("code"));
        Map<String, Object> map = new HashMap<>();
        map.put("code", resultMap.get("code"));
        map.put("msg", resultMap.get("msg"));

        String json = JSON.toJSONString(map);

        // 将 JSON 字符串写入响应
        resp.getWriter().write(json);

        // 如果登录成功，设置 session 属性
        if ("0000".equals(resultMap.get("code"))) {
            Employee employee = employeeService.getEmployeeInfo(name);
            req.getSession().setAttribute("employee", employee);
        } else {
            resp.sendRedirect("login.jsp");
        }

        System.out.println("13456484964165811");

//        //页面跳转
//        req.getSession().setAttribute("resultMap",resultMap);
//        String code = resultMap.get("code").toString();
//        if("0000".equals(code)){
//            Employee employee = employeeService.getEmployeeInfo(name);
//            req.getSession().setAttribute("employee",employee);
//
//            //登录时将部门集合 还有岗位集合查询共享
//
//
////            resp.sendRedirect("index.jsp");
//            req.getRequestDispatcher("/queryEmp").forward(req,resp);
//        }else{
//            resp.sendRedirect("login.jsp");
//        }

        System.out.println("ftuftu");
    }
}
